#!/bin/bash

# 得到当前目录
scriptDir=$(dirname "$(realpath "$0")")

# 两个参数
cmd=$1
AppName=$2

if [ $1 -eq "" ]; then
	echo "please input start|stop|restart"
	exit 1
fi

# JVM设置
JVM_OPTS="-Dname=$AppName  -Duser.timezone=Asia/Shanghai -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=512m -XX:+HeapDumpOnOutOfMemoryError  -XX:+PrintGCDetails -XX:NewRatio=1 -XX:SurvivorRatio=30 -XX:+UseParallelGC"


start(){
	echo "Starting $AppName, please wait."
	PID=`ps -ef | grep $AppName | grep -v 'grep' | awk '{print $2}'`

	if [ x"$PID" != x"" ]; then
		echo "$AppName is running !!!"
	else
		nohup java $JVM_OPTS -jar $AppName >> $LOG_PATH 2>&1 &
		PID=`ps -ef | grep $AppName | grep -v 'grep' | awk '{print $2}'`
		echo $PID>$scriptDir/pid
		echo $version>$scriptDir/version
		echo "Start $AppName success with pid $PID"
	fi
}


stop(){
	PID=$(cat $scriptDir"/pid")
	if [ "$PID" = "0" ]; then
		echo "there is no pid in the pidFile, application may stopped"
	else
		echo "get pid from pidFile with $PID"
	fi

	if [ x"$PID" != x"" ]; then
		kill -TERM $PID
		while ps -p $PID > /dev/null ; do
			sleep 1
		done
		echo "App stopped."
	else
		echo "App already stopped"
	fi

	echo "0">pid
}


status(){
	PIDs=`ps -ef |grep java|grep -F $AppName|grep -v grep|wc -l`
    if [ $PIDs != 0 ];then
        PID=`ps -ef |grep java|grep -F $AppName|grep -v grep|awk '{print $2}'`
        echo "$AppName is running with pid $PID"
    else
        echo "$AppName is not running"
    fi
}


getPid(){
	return `ps -ef | grep -F $AppName | grep -v 'grep' | awk '{print $2}'`
}


case $1 in
    start) start;;
    stop) stop;;
    status) status;;
    *)
esac
